﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace ArgusLib.Controls
{
	public class TextChecker
	{
		#region Properties
		Control control;
		public virtual Control Control
		{
			get { return this.control; }
			set
			{
				if (this.control != null)
				{
					this.control.TextChanged -= control_TextChanged;
					this.control.KeyPress -= control_KeyPress;
				}

				this.control = value;
				if (this.control != null)
				{
					this.control.TextChanged += control_TextChanged;
					this.control.KeyPress += control_KeyPress;
				}
			}
		}

		public bool CheckKeyPress { get; set; }

		public IEnumerable<CharSet> AllowedChars { get; set; }
		#endregion

		#region Constructors
		public TextChecker()
			: this(null, null) { }

		public TextChecker(Control control, IEnumerable<CharSet> allowedChars)
		{
			this.Control = control;
			this.AllowedChars = allowedChars;
			this.CheckKeyPress = true;
		}
		#endregion

		#region Non-Public Methods
		void control_TextChanged(object sender, EventArgs e)
		{
			if (this.AllowedChars.ContainsUnallowedChars(this.Control.Text) == true)
			{
				this.Control.Text = this.AllowedChars.RemoveUnallowedChars(this.Control.Text);
			}
			else
			{
				this.OnTextChanged(EventArgs.Empty);
			}
		}

		void control_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (this.CheckKeyPress == false)
				return;
			if (char.IsControl(e.KeyChar) == true)
				return;

			e.Handled = !this.AllowedChars.Check(e.KeyChar);
		}
		#endregion

		#region Events
		public event EventHandler TextChanged;

		protected virtual void OnTextChanged(EventArgs e)
		{
			if (this.TextChanged != null)
				this.TextChanged(this.Control, e);
		}
		#endregion
	}
}
